import NumberAnimate from "../../utils/NumberAnimate";
const imageCdn = 'https://tdesign.gtimg.com/mobile/demos';

const { imageUrl } = require('../../utils/http/http').dev
const {
  getMeetingNews,
  getMeetingPeople,
  getHighlightList,
  getConferenceInfoList,
  getWonderfulImageList,
  getInteraction,
  getActivityByPageSize
} = require("../../utils/http/api")
const tool = require("../../utils/tool")
const swiperList = [{
    value: `http://117.72.64.158:9002/xhlj-webapp-image/2025/10/07/a284aa8e2fef4de5a36b4221d1c28bfd.jpg`,
    ariaLabel: '图片1',
  }
];
const app = getApp()
// 首节流
function throttle(fn, interval) {
  var enterTime = 0; //触发的时间
  var gapTime = interval || 10000; //间隔时间，如果interval不传，则默认300ms
  return function () {
    var context = this;
    var backTime = new Date(); //第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context, arguments);
      enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    manyImage:imageUrl + "/大于.png",
    liveImage: imageUrl + "/living.png",
    collectImage: imageUrl + "/collection.png",
    highList: [],
    //获取全局变量 导航栏的高度statusBarHeight
    top: Number(app.globalData.menu.top),
    height: Number(app.globalData.menu.height),
    bottom: Number(app.globalData.menu.bottom),
    scrollTop: 0,
    windowWidth: 0,
    num1: 500,
    num2: 10000,
    num3: 2500,
    num4: 550,
    current: 0,
    // 轮播配置
    autoplay: true,
    duration: 500,
    interval: 5000,
    swiperList,
    swiperHeight: 210,
    peolpeList: {},
    // 绿色新闻动态
    newsList: [],
    people: [],
    // 绿色新闻活动
    activity: [{
      id: 0,
      image: "https://obs-xhlj.obs.cn-east-3.myhuaweicloud.com/2024/4/660cd4a277ef4e45bd16d696cf1b846a.jpg",
      title: "绿色环保活动安全特训营·数据要素X高级研修班",
      time: "2024-04-07"
    }, {
      id: 0,
      image: "	https://obs-xhlj.obs.cn-east-3.myhuaweicloud.com/2024/4/cd1d676212094d579358b8d3b3011351.jpg",
      title: "绿色环保活动安全特训营·AI新质生产力-大模型认知与应用能力提升班",
      time: "2024-04-07"
    }],
    exciting: [
      'https://obs-xhlj.obs.cn-east-3.myhuaweicloud.com/2024/4/089b044bc0ad4281ae202b856f1fca95.jpg',
      'https://img2023.gcsis.cn/2024/4/0c077d696db94a9c86e0cccd5ca41673.jpg',
      'https://img2023.gcsis.cn/2023/3/e717194cfbcf4b668b792376ce41a52f.jpg',
      'https://img2023.gcsis.cn/2024/4/0c077d696db94a9c86e0cccd5ca41673.jpg',
      'https://img2023.gcsis.cn/2023/3/e717194cfbcf4b668b792376ce41a52f.jpg',
      'https://obs-xhlj.obs.cn-east-3.myhuaweicloud.com/2024/4/089b044bc0ad4281ae202b856f1fca95.jpg',
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    // 交叉观察器的典型用途：监听某个元素是否进入或离开屏幕。
    _this._observer = wx.createIntersectionObserver()
    _this._observer
      //.relativeTo('.scroll-view')
      .relativeToViewport() //指定页面显示区域作为参照区域之一
      .observe('.number', (res) => { //在参照区域里监听目标节点是否显示
        // console.log(res);
        if (res.intersectionRatio > 0) {
          _this.throttleNumber()
        }
      })
    // 获取新闻
    _this.getNewsList()
    // 检测用户登录缓存状态
    _this.judgeUer()
    // 获取绿色新闻嘉宾
    _this.getPeopleList()
    // 获取亮点
    _this.getHighlightList()
    //精彩瞬间(图片)
    _this.getWonderfulImageList()
    //活动列表
    _this.getActivityByPageSize()
  },
  
  getActivityByPageSize(){
    let _this = this;
    getActivityByPageSize(2).then((res) => {  
      if (res && res.rows) {  // 确保res和res.data都存在  
        const activityList = res.rows;  
        console.log("活动列表", activityList);
        activityList.forEach((item)=>{
          let image = item.activityImage.split(",")
          item.activityImageFirst = image[0]
        })
        activityList.forEach((item)=>{
          let image = item.activityImage.split(",")
          item.activityImageFirst = image[0]
        })
        _this.setData({  
          activityList: activityList,
          nearAct: activityList[4]
        });
      }  
    }).catch((error) => {  
      console.error('请求活动详情失败:', error);  
    });  
  },
  // 切换嘉宾{
  changePeople(e) {
    let index = parseInt(e.currentTarget.dataset.id)
    const {
      people
    } = this.data
    let peolpeList = people[index]
    this.setData({
      peolpeList,
      current: index
    })
  },
  // 活动详情页
  goActiveDetail(e){
    console.log("跳转活动详情页面",e)
    let item = e.currentTarget.dataset.item
    if(item.activityType == 0){
      wx.navigateTo({
        url: '../index/live/live?activityId='+ item.activityId,
      })
    }else{
      wx.navigateTo({
        url: '../activeDetail/activeDetail?url='+ item.activityImage,
      })
    }
  },
  // 滑动距离
  onPageScroll: function (res) {
    // console.log("滑动", res, parseInt(res.scrollTop));
    this.setData({
      scrollTop: parseInt(res.scrollTop)
    })
  },
  imgLoad(e) {
    let id = e.currentTarget.dataset.id
    var that = this;
    wx.getSystemInfo({
      success(res) {
        var windowWidth = parseInt((res.windowWidth * 0.92 - 20) / 3);
        that.setData({
          windowWidth
        })
      }
    })
  },

  // 数字自动累加
  numberAdd() {
    const {
      num1,
      num2,
      num3,
      num4
    } = this.data
    let n1 = new NumberAnimate({
      from: num1, //开始时的数字
      speed: 2000, // 总时间
      refreshTime: 100, //  刷新一次的时间
      decimals: 0, //小数点后的位数
      onUpdate: () => { //更新回调函数
        this.setData({
          num1: n1.tempValue
        });
      },
      onComplete: () => { //完成回调函数
        // console.log("完成时间累加")
      }
    });
    let n2 = new NumberAnimate({
      from: num2, //开始时的数字
      speed: 2000, // 总时间
      refreshTime: 100, //  刷新一次的时间
      decimals: 0, //小数点后的位数
      onUpdate: () => { //更新回调函数
        this.setData({
          num2: n2.tempValue
        });
      },
      onComplete: () => { //完成回调函数
        // console.log("完成时间累加")
      }
    });
    let n3 = new NumberAnimate({
      from: num3, //开始时的数字
      speed: 2000, // 总时间
      refreshTime: 100, //  刷新一次的时间
      decimals: 0, //小数点后的位数
      onUpdate: () => { //更新回调函数
        this.setData({
          num3: n3.tempValue
        });
      },
      onComplete: () => { //完成回调函数
        // console.log("完成时间累加")
      }
    });
    let n4 = new NumberAnimate({
      from: num4, //开始时的数字
      speed: 2000, // 总时间
      refreshTime: 100, //  刷新一次的时间
      decimals: 0, //小数点后的位数
      onUpdate: () => { //更新回调函数
        this.setData({
          num4: n4.tempValue
        });
      },
      onComplete: () => { //完成回调函数
        // console.log("完成时间累加")
      }
    });
  },

  // 绿色新闻新闻列表
  goNewsList() {
    wx.navigateTo({
      url: '../newsList/newsList',
    })
  },
  /**
   * 获取新闻列表
   */
  getNewsList() {
    let _this = this
    getMeetingNews().then((res) => {
      if (res.rows.length > 0) {
        const newsList = res.rows.splice(0, 3)
        newsList.forEach((item) => {
          item.createTime = tool.changeTime(item.createTime, 10)
          if (item.newsImage != undefined) {
            item.newsImage = item.newsImage.split(',')
          }
        })
        _this.setData({
          newsList
        })
      }
    })
  },

  // 绿色新闻活动列表
  goActivityList() {
    wx.navigateTo({
      url: '../active/active',
    })
    
  },

  // 绿色新闻嘉宾列表
  goPeopleList() {
    wx.navigateTo({
      url: '../peopleList/peopleList',
    })
  },
  // 获取绿色新闻嘉宾
  getPeopleList() {
    let _this = this
    getMeetingPeople().then(res => {
      if (res.rows.length > 0) {
        const people = res.rows.splice(0, 8)
        let obj = people[0]
        people.forEach(item => {
          item.participantsContent = tool.changeDetails(item.participantsContent, 15)
        })
        _this.setData({
          people: people,
          peolpeList: obj
        })
      }
    })
  },
  // 绿色新闻亮点列表 
  goHighlightsList() {
    wx.navigateTo({
      url: '../highlightsList/highlightsList',
    })
  },
  // 获取绿色新闻亮点
  getHighlightList() {
    let _this = this
    getHighlightList().then(res => {
      if (res.rows.length > 0) {
        const highList = res.rows
        highList.forEach(item => {
          item.highlightContent = tool.changeDetails(item.highlightContent, 15)
        })
        _this.setData({
          highList
        })
      }
    })
  },
  // 绿色新闻精彩瞬间
  goExcitingList() {
    wx.navigateTo({
      url: '../excitingList/excitingList',
    })
  },
  // 获取精彩瞬间(图片)
  getWonderfulImageList() {
    wx.showLoading({
      title: '加载中...',
    });
    let _this = this;
    getWonderfulImageList().then(res => {
      if (res.rows && res.rows.length > 0) {
        const imageList = res.rows;
        console.log("绿色新闻精彩瞬间图片：", imageList);
        _this.setData({
          imageList
        });
        wx.hideLoading();
      }
    }).catch(error => {
      console.error("获取精彩瞬间图片失败：", error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      wx.hideLoading();
    });
  },
 
  // 关于绿色新闻列表
  goAboutList() {
    wx.navigateTo({
      url: '../luanyeNet/luanyeNet',
    })
  },
 
  //参会指南
  gotoRelease() {
    wx.navigateTo({
      url: '/pages/index/conferenceGuide/conferenceGuide',
    })
  },
  // 节流
  throttleNumber: throttle(function () {
    this.numberAdd()
  }),

  /**
   * 检测用户信息
   */
  judgeUer() {
    let imutUser = wx.getStorageSync('imutUser')
    let userInfo = wx.getStorageSync('userInfo')
    if (!imutUser || !userInfo) {
      wx.reLaunch({
        url: '../initialize/initialize',
      })
    }
  },

  //绿色新闻直播
  onLive() {
    let isSms = wx.setStorageSync('sms')
    console.log("isSms",isSms)
    if(isSms){
      wx.navigateTo({
        url: '/pages/index/liveList/liveList',
      });
    }else{
      wx.navigateTo({
        url: '/pages/sms/sms',
      })
    }
    
  },
  //绿色新闻日程
  onPlan() {
    wx.navigateTo({
      url: '/pages/index/plan/plan',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //停止监听
    if (this._observer) this._observer.disconnect()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})